package com.jamal2362.apktool.task;

import android.content.Context;
import brut.util.OS;
import java.io.File;
import com.jamal2362.apktool.R;
import com.jamal2362.apktool.fragment.files.Refreshable;
import com.jamal2362.apktool.util.FileUtils;
import com.jamal2362.apktool.util.TextUtil;
import com.jamal2362.apktool.util.sai.Installer;

public class SAITask extends AbstractTask {
	private Context context;
	private SignUtil signTool;
	private File[] exFiles;
	private File tempDir;
	private boolean mSign;

	public SAITask(Context ctx, Refreshable refresh, SignUtil signTool, boolean sign) {
		super(ctx, refresh);
		this.context = ctx;
		this.signTool = signTool;
		this.mSign = sign;
	}

	@Override
	protected int getTitle() {
		return R.string.split_install;
	}

	@Override
	protected boolean process(File f) {
		return true;
	}

	@Override
	protected Boolean doInBackground(File[] p1) {
		tempDir = p1[0].getParentFile();
		if (mSign) {
			info(R.string.sign_run_title, (Object) null);
			exFiles = new File[p1.length];
			for (int i = 0; i < p1.length; i++) {
				File out = getOutFile(p1[i], p1[i].getName());
				if (!signTool.sign(p1[i], out, 14, this)) {
					return false;
				} else {
					exFiles[i] = out;
					p1[i].delete();
				}
			}
		} else {
			exFiles = p1;
		}
		info(R.string.split_install, (Object) null);
		Installer inst = new Installer(context);
		inst.installApk(exFiles);
		return true;
	}

	@Override
	protected void onPostExecute(Boolean result) {
		OS.rmdir(tempDir);
		TextUtil.st(context, context.getString(R.string.split_install_toast));
		super.onPostExecute(result);
	}

	@Override
	protected boolean shouldShowFinishDialog() {
		return false;
	}

	public File getOutFile(File f, String name) {
		String dir = f.getParent();
		if (name == null)
			name = f.getName();
		name = FileUtils.genNameApk(context, dir, name, "_sign", 0);
		return new File(dir, name);
	}
}
